﻿using ElectronicShoppingMall.Service.Models.Enterprise;
using ElectronicShoppingMall.Service.Services.Enterprise;
using ElectronicShoppingMall.Web.Back.Filter;
using ElectronicShoppingMall.Web.Back.DTOS;
using Extension;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;

namespace ElectronicShoppingMall.Web.Back.Controllers
{
    public class EmployeeController : ApiController
    {
        private MenuService _serviceMenu = new MenuService();
        private EmployeeUserService _serviceUser = new EmployeeUserService();
        /// <summary>
        /// 获取当前登录用户的菜单
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.Authorize]
        public MenuDTO GetMenu()
        {
            string auth = Request.Headers.Authorization.ToString();
            MenuModel result = _serviceMenu.CreateMenuModel(ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId);
            MenuDTO model = new MenuDTO()
            {
                MenuId = result.MenuId,
                MenuName = result.MenuName,
                Route = result.Route,
                PermissionCode = result.PermissionCode,
                Childrens = GetChildrens(result.Childrens)
            };

            return model;
        }
        //获取菜单的子节点的菜单
        private List<MenuDTO> GetChildrens(List<MenuModel> childrens)
        {
            List<MenuDTO> childrensMenu = new List<MenuDTO>();
            foreach (var childrenMenu in childrens)
            {
                MenuDTO temp = new MenuDTO()
                {
                    MenuId = childrenMenu.MenuId,
                    MenuName = childrenMenu.MenuName,
                    Route = childrenMenu.Route,
                    PermissionCode = childrenMenu.PermissionCode,
                    Childrens = GetChildrens(childrenMenu.Childrens),

                };
                childrensMenu.Add(temp);

            }
            return childrensMenu;
        }
        /// <summary>
        /// 获取当前登录用户的权限
        /// </summary>
        /// <returns></returns>
        [System.Web.Mvc.Authorize]
        public List<EmployeeUserPermissionDTO> GetPermissions()
        {
            List<EmployeeUserPermissionDTO> permissions = new List<EmployeeUserPermissionDTO>();
            string auth = Request.Headers.Authorization.ToString();
            var result = _serviceMenu.GetMenuPermission(ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId);
            foreach (var item in result)
            {
                EmployeeUserPermissionDTO temp = new EmployeeUserPermissionDTO()
                {
                    Name = item.Name,
                    PermissionId = item.PermissionId,
                    PermissionRoute = item.PermissionRoute
                };
                permissions.Add(temp);
            }
            return permissions;
        }
        /// <summary>
        /// 获取当前用户详细信息
        /// </summary>
        /// <returns></returns>
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpGet]
        public UserInformationDTO GetUserInformation()
        {
            string auth = Request.Headers.Authorization.ToString();
            var result = _serviceUser.GetEmployeeUserInformation(ExtensionMethods.GetEmployeeUserObject(auth).UserId, ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId);
            UserInformationDTO user = new UserInformationDTO()
            {
                Account = result.Account,
                Birthday = DateTime.Parse(result.Birthday + "").ToString("yyyy - MM - dd"),
                Email = result.Email,
                Gender = result.Gender == true ? "男" : "女",
                NickName = result.NickName,
                Password = result.NickName,
                PhoneNumber = result.PhoneNumber,
                UserAvatar = result.UserAvatar,
                UserId = result.UserId,
                CreateTime = result.CreateTime,
                Position = result.Position
            };

            return user;
        }
        //更改用户头像
        [System.Web.Mvc.HttpPost]
        public UserInformationDTO ChangeUserAvatar([FromBody]string imgBase)
        {
            string auth = Request.Headers.Authorization.ToString();
            var result = _serviceUser.ChangeUserAvatar(ExtensionMethods.GetEmployeeUserObject(auth).UserId, ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId, imgBase);
            if (result != null)
            {
                UserInformationDTO user = new UserInformationDTO()
                {
                    Account = result.Account,
                    Birthday = DateTime.Parse(result.Birthday + "").ToString("yyyy - MM - dd"),
                    Email = result.Email,
                    Gender = result.Gender == true ? "男" : "女",
                    NickName = result.NickName,
                    Password = result.NickName,
                    PhoneNumber = result.PhoneNumber,
                    UserAvatar = result.UserAvatar,
                    UserId = result.UserId,
                    CreateTime = result.CreateTime,
                    Position = result.Position
                };

                return user;
            }
            else
            {
                return null;
            }
        }
        [System.Web.Mvc.HttpPost]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        //更改用户信息
        public UserInformationDTO ChangeUserDetails(UserDetailsDTO userDetails)
        {
            string auth = Request.Headers.Authorization.ToString();
            UserDetailsModel result = new UserDetailsModel()
            {
                NickName = userDetails.NickName,
                Gender = userDetails.Gender,
                Birthday = userDetails.Birthday,
                PhoneNumber = userDetails.PhoneNumber,
                Email = userDetails.Email
            };
            var user = _serviceUser.ChangeUserDetails(ExtensionMethods.GetEmployeeUserObject(auth).UserId, ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId, result);
            if (user != null)
            {
                UserInformationDTO userData = new UserInformationDTO()
                {
                    Account = user.Account,
                    Birthday = DateTime.Parse(user.Birthday + "").ToString("yyyy - MM - dd"),
                    Email = user.Email,
                    Gender = user.Gender == true ? "男" : "女",
                    NickName = user.NickName,
                    Password = user.NickName,
                    PhoneNumber = user.PhoneNumber,
                    UserAvatar = user.UserAvatar,
                    UserId = user.UserId,
                    CreateTime = user.CreateTime,
                    Position = user.Position
                };
                return userData;
            }
            else
                return null;
        }
        //获取系统角色
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpPost]
        [EmployeePermission(PermissionCode = Permissions.RoleManagement)]
        public List<RoleDTO> GetRoles()
        {
            List<RoleDTO> result = new List<RoleDTO>();
            var roles = _serviceUser.GetRoles();
            foreach (var role in roles)
            {
                RoleDTO temp = new RoleDTO()
                {
                    RoleId = role.RoleId,
                    Name = role.Name,
                    IsStatic = role.IsStatic,
                    CreationTime = role.CreationTime.ToString()
                };
                result.Add(temp);
            }
            return result;
        }
        //获取角色的权限
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpGet]
        [EmployeePermission(PermissionCode = Permissions.RoleManagement)]
        public List<EmployeeUserPermissionDTO> GetPermisson(string roleId)
        {
            List<EmployeeUserPermissionDTO> result = new List<EmployeeUserPermissionDTO>();
            int id = Convert.ToInt32(roleId);
            var permissions = _serviceUser.GetPermissonByRoleId(id);
            foreach (var per in permissions)
            {
                EmployeeUserPermissionDTO temp = new EmployeeUserPermissionDTO()
                {
                    PermissionId = per.PermissionId,
                    Name = per.Name,
                    PermissionRoute = per.PermissionRoute
                };
                result.Add(temp);
            }
            return result;
        }
        //配置角色的权限
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpPost]
        [EmployeePermission(PermissionCode = Permissions.RoleManagement)]
        public List<RoleDTO> ChangeRolePermission(RolePermissionDTO rolePer)
        {
            try
            {
                List<int> permissionIds = new List<int>();
                foreach (var per in rolePer.Permissions)
                {
                    permissionIds.Add(Convert.ToInt32(per.Id));
                }
                if (rolePer.RoleId != "-1")
                {
                    _serviceUser.ChangeRolePermission(Convert.ToInt32(rolePer.RoleId), rolePer.RoleName, permissionIds);
                }
                else
                {
                    _serviceUser.AddRole(rolePer.RoleName, permissionIds);
                }
                return GetRoles();
            }
            catch
            {
                return null;
            }
        }
        //删除角色
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpDelete]
        [EmployeePermission(PermissionCode = Permissions.RoleManagement)]
        public List<RoleDTO> DeleteRole([FromBody]string roleId)
        {
            try
            {
                _serviceUser.DeleteRoleByRoleId(Convert.ToInt32(roleId));
                return GetRoles();
            }
            catch (Exception e)
            {
                return null;
            }
        }
        //获取所有的员工信息
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpGet]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        public List<EmployeeUserDetailsDTO> GetAllEmployeeUser()
        {
            List<EmployeeUserDetailsDTO> result = new List<EmployeeUserDetailsDTO>();
            var users = _serviceUser.GetAllEmployeeUser();
            foreach (var user in users)
            {
                EmployeeUserDetailsDTO temp = new EmployeeUserDetailsDTO()
                {
                    UserId = user.UserId,
                    EmployeeId = user.EmployeeId,
                    Account = user.Account,
                    CreateTime = user.CreateTime.ToString(),
                    Email = user.Email,
                    Password = user.Password,
                    NickName = user.NickName,
                    Gender = user.Gender,
                    IsActivate = user.IsActivate,
                    Birthday = user.Birthday.ToString(),
                    PhoneNumber = user.PhoneNumber,
                    LastLoginTime = user.LastLoginTime,
                    LastLoginIpAndAddress = user.LastLoginIpAndAddress,
                    RoleName = user.RoleName
                };
                result.Add(temp);
            }
            return result;
        }
        //管理员更改员工的信息
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpPost]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        public List<EmployeeUserDetailsDTO> AdminChangeUserDetails(EmployeeUserDetailsChangeDTO user)
        {
            try
            {
                EmployeeUserDetailsModel userInfo = new EmployeeUserDetailsModel()
                {
                    UserId = user.UserId,
                    Account = user.Account,
                    Email = user.Email,
                    Password = user.Password,
                    NickName = user.NickName,
                    PhoneNumber = user.PhoneNumber,
                    IsSendMail = user.IsSendMail
                };
                if (user.IsNew == "new")
                {
                    _serviceUser.AdminAddEmployee(userInfo, user.UserRoles);
                }
                else
                {
                    _serviceUser.AdminChangeUserDetails(userInfo, user.UserRoles);
                }
                return GetAllEmployeeUser();
            }
            catch 
            {
                return null;
            }

        }

        //获取用户的特殊权限
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpGet]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        public List<EmployeeUserPermissionDTO> GetUserPermissions(string employeeId)
        {
            try
            {
                var permisssions = _serviceUser.GetUserPermissions(Convert.ToInt32(employeeId));
                if (permisssions == null)
                {
                    return null;
                }
                else
                {
                    List<EmployeeUserPermissionDTO> result = new List<EmployeeUserPermissionDTO>();
                    foreach (var per in permisssions)
                    {
                        EmployeeUserPermissionDTO temp = new EmployeeUserPermissionDTO()
                        {
                            Name = per.Name,
                            PermissionId = per.PermissionId,
                            PermissionRoute = per.PermissionRoute
                        };
                        result.Add(temp);
                    }
                    return result;
                }
            }
            catch
            {
                return null;
            }

        }

        //修改用户的特殊权限
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpPost]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        public IHttpActionResult ChangeEmployeePermissions(EmployeePermissionDTO employeePer)
        {
            try
            {
                _serviceUser.ChangeEmployeePermissions(employeePer.EmployeeId, employeePer.PermissionIds);
                return Ok("success");
            }
            catch
            {
                return null;
            }
        }

        //删除员工用户
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpDelete]
        [EmployeePermission(PermissionCode = Permissions.UserManagement)]
        public List<EmployeeUserDetailsDTO> DeleteEmployeeUser([FromBody]int userId)
        {
            try
            {
                _serviceUser.DeleteEmployeeUser(userId);
                return GetAllEmployeeUser();
            }
            catch
            {
                return null;
            }

        }
        //获取操作日志
        [System.Web.Mvc.Authorize]
        [System.Web.Mvc.HttpGet]
        [EmployeePermission(PermissionCode = Permissions.OperationLogView)]
        public List<AdminLogModel> GetOperationLogs()
        {
            try
            {
                return _serviceUser.GetOperationLogs();
            }
            catch
            {
                return null;
            }
        }
    }
}
